package com.idis.dbApp.controller;

import com.idis.common.util.ImgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by Ming on 2018/2/4.
 */
@RestController
@RequestMapping("/image")
@Api(tags = "图像接口")
public class PictureController {

    @ApiOperation("保存图像")
    @PostMapping("/{name}.{ext}")
    public String saveImg(@ApiParam("图像资源输入流")@RequestPart InputStreamResource image, @ApiParam("图像名称")@PathVariable String name, @ApiParam("图像文件后缀名")@PathVariable String ext) throws IOException {
        return ImgUtil.savePicture(image.getInputStream(),name,ext);
    }

    @ApiOperation("获取图像")
    @GetMapping("/{name}.{ext}")
    public ResponseEntity<byte[]> getImg(@ApiParam("图像文件名")@PathVariable String name, @ApiParam("图像文件后缀名")@PathVariable String ext, HttpServletResponse response) throws IOException {
        File file=new File("img/"+name+"."+ext);
        FileInputStream inputStream=new FileInputStream(file);
        byte[] bs=new byte[inputStream.available()];
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type","image/png");
        inputStream.read(bs);
        HttpStatus status=HttpStatus.OK;
        ResponseEntity<byte[]> entity =new ResponseEntity<>(bs,headers,status);
        inputStream.close();
        return entity;
    }
}
